<!-- 新增/编辑全委通知 -->
<template>
	<view class="mainPge">
		<!-- 公共头部 -->
		<headerPublic title="请假申请" @backfn="backfn" />
		<!--主体-->
		<view class="page-content outbottom">
			<view class="frct">
				<view class="fr-row frit">
					<view class="fr-lable fr-2">
						创建部门
						<text class="redico">*</text>
					</view>
					<uv-input border="none" v-model="pageInfo.deptName" readonly></uv-input>
				</view>
				<view class="fr-row frit">
					<view class="fr-lable fr-2">
						创建日期
						<text class="redico">*</text>
					</view>
					<view class="defaultstr" @click="$refs.datetimePicker.open()" >{{ pageInfo.createTime }}</view>
				</view>
				<view class="fr-row frit">
					<view class="fr-lable fr-2">
						创建人
						<text class="redico">*</text>
					</view>
					<uv-input border="none" v-model="pageInfo.agentName" readonly></uv-input>
				</view>
				<view class="fr-row frit">
					<view class="fr-lable fr-2">联系电话</view>
					<uv-input border="none" v-model="pageInfo.telephone" readonly></uv-input>
				</view>
			</view>
			<view class="frct">
				<view class="fr-colum">
					<view class="fr-lable">
						<text class="redico">*</text>
						请假原因：
					</view>
					<uv-textarea v-model="pageInfo.content" placeholder="请输入请假原因" :maxlength="-1" autoHeight
						style="margin-bottom: 10px"></uv-textarea>
				</view>
			</view>
			<view class="frct">
				<view class="fr-row frit" @click="$refs.picker.open()">
					<view class="fr-lable fr-2">
						请假类型
						<text class="redico">*</text>
					</view>
					<view class="fr-row fr-left" v-if="!pageInfo.holidayTypeName">
						<text class="qxzstr">请选择</text>
						<uv-icon name="arrow-right"></uv-icon>
					</view>
					<view class="fr-row" v-else style="width: 60%;">
						<text class="defaultstr">{{ pageInfo.holidayTypeName }}</text>
					</view>
				</view>
				<view class="fr-row frit" @click="opendateTime('startTime')">
					<view class="fr-lable fr-2">
						请假开始时间
						<text class="redico">*</text>
					</view>
					<view class="fr-row  fr-left" v-if="!pageInfo.startTime">
						<text class="qxzstr">请选择</text>
						<uv-icon name="arrow-right"></uv-icon>
					</view>
					<view class="fr-row fr-left" v-else>
						<text class="defaultstr">{{ pageInfo.startTime }}</text>
					</view>
				</view>
				<view class="fr-row frit" @click="opendateTime('endTime')">
					<view class="fr-lable fr-2">
						请假结束时间
						<text class="redico">*</text>
					</view>
					<view class="fr-row  fr-left" v-if="!pageInfo.endTime">
						<text class="qxzstr">请选择</text>
						<uv-icon name="arrow-right"></uv-icon>
					</view>
					<view class="fr-row fr-left" v-else>
						<text class="defaultstr">{{ pageInfo.endTime }}</text>
					</view>
				</view>
			</view>
			<view class="frct">
				<view class="fr-colum">
					<view class="fr-row fr-lable fr-2 fr-2-line">
						<text>附件</text>
						<DhUpload style="flex: none" upload-type="HOLIDAY" :business-id="pageInfo.businessId"  @upload-success="handleFilesSuccess"  :selected-files="fileListFJ">
							<template #trigger="{ selectFile }">
							     <text class="c1">+添加</text>
							  </template>
						</DhUpload>
					</view>
					<view class="fiellist">
						<view class="fr-row flieit" v-for="(file, index) in fileListFJ" :key="index">
							<text class="tname">{{ file.fileName }}</text>
							<text class="tsize">{{ file.fileSize }}</text>
							<uv-icon name="close" color="#2D75D7" size="14" @click="deleteFile(index)"></uv-icon>
						</view>
					</view>
				</view>
			</view>
			<view class="frct">
				<view class="fr-colum">
					<view class="fr-lable">
						<text class="redico">*</text>
						选择路径：
					</view>
					<uv-radio-group v-model="pageInfo.businessStatusName" class="bline">
						<uv-radio size="15" activeColor="#2d75d7" :customStyle="{ margin: '8px' }"
							v-for="(item, index) in radiolist3" :key="index" :label="item.name" :name="item.name"
							@change="businessStatuschange"></uv-radio>
					</uv-radio-group>
					<view class="choseP" v-if="pageInfo.businessStatus == 'UNDO'">
						<view class="itp" v-for="(item, index) in auditarry" :key="index">
							<image src="/static/docmumentImg/ico-defalutp.png" class="icopimg"></image>
							<text class="t1">{{ item }}</text>
							<image src="/static/docmumentImg/icdelt.png" class="icdelt"
								@click="deletPerson(index, item)"></image>
						</view>
						<view class="itp" @click="getPerson('添加审核人')">
							<image src="/static/docmumentImg/ico-addp.png" class="icopimg"></image>
							<text class="t2">添加审核人</text>
						</view>
					</view>
				</view>
			</view>
		</view>
		<!--底部固定 -->
		<view class="bt-foot">
			<view class="bt bt1" @click="sumitFn('保存')" v-if="(tabtype == 'icreat' && (businessStatus == 'DRAFT' || businessStatus == 'REBACK')) || actionType == 'add'">
				保存
			</view>
			<view class="bt bt2" @click="sumitFn('提交')">提交</view>
		</view>
		<!--- 日期时间选择器 -->
		<uv-datetime-picker ref="datetimePicker" mode="datetime" @confirm="datetimeconfirm" v-model="timevalue"></uv-datetime-picker>
		<!-- 请假类型-->
		<uv-picker ref="picker" :columns="holidaytypelist" keyName="label" @confirm="qjlxconfirm"></uv-picker>
	</view>
</template>

<script>
	import {timeFormat} from '@/uni_modules/uv-ui-tools/libs/function/index.js';
	import {getauditInfo,getSaveDrafat,handelauditSubmit} from '@/api/applicationleave.js';
	import {getRequestUrl} from '@/utils/request.js'
	export default {
		name: 'noticeset',
		data() {
			return {
				actionType: 'add', //判断（seeinfo）是查看详情还是（add）新增还是（edit）编辑
				businessId: '', // 页面传过来的id只有查看和编辑的时候才使用业务id
				businessType: 'HOLIDAY', //业务类型 all 是全委通知  这块可以默认为all了
				businessStatus: '',
				tabtype: 'notice', // 判断是那个tab的处理数据执行（notice是待处理的 icreat是我创建的 iagreen是我审批的）用来做一些字段显示隐藏
				pageInfo: {
					businessId: '', //业务id
					businessType: '', //业务状态
					// 基本信息数据
					deptName: '', // 创建部门
					createTime: '', // 创建日期
					agentName: '', // 经办人
					telephone: '', //联系电话
					content: '', // 请假原因
					holidayType: "", //请假类型
					holidayTypeName: '', //
					startTime: "", //请假开始时间
					endTime: "", //请假结束时间
					businessStatus: '', //选择路径
					businessStatusName: '', //选择路径名称--选送审才有添加处理人，结束流程没有没有
					auditorIds: '', // 添加审批人ids
					auditorNames: '', // 审批人名称
					auditorAccounts: '', // 添加审批人的手机号（账号）
					busiAttachIds: '' // 文件ids
				},
				dateTimeTpey: '', // 判断是选择请假开始时间还是结束时间
				auditarry: [], // 页面用来显示的审批人数组
				fileListFJ: [], // 附件上传
				holidaytypelist: [
					[{
							label: "事假",
							id: "Personal"
						}, {
							label: "年假",
							id: "Annual"
						}, {
							label: "病假",
							id: "Sick"
						},
						{
							label: "其它（婚假、育儿假、丧假）",
							id: "Other"
						}
					]
				],
				radiolist3: [{
						name: '送审',
						disabled: false
					},
					{
						name: '结束流程',
						disabled: false
					}
				],
				timevalue:Number(new Date()),// 默认显示的时间 
			};
		},
		onLoad(res) {
			this.actionType = res.actionType ? res.actionType : 'add';
			this.businessId = res.businessId ? res.businessId : '';
			this.businessType = res.businessType ? res.businessType : 'HOLIDAY';
			this.businessStatus = res.businessStatus ? res.businessStatus : '';
			this.tabtype = res.tabtype ? res.tabtype : 'notice';
			this.Init();
		},
		onShow() {
			this.circulateSumint();
		},
		methods: {
			Init() {
				this.getpageInfo();
			},
			// 删除审核人
			deletPerson(index) {
				const fields = ['auditorIds', 'auditorNames', 'auditorAccounts'];
				fields.forEach(key => {
					this.pageInfo[key] = (this.pageInfo[key] || '').split(',').filter((_, i) => i !== index).join(',');
				});
				this.auditarry.splice(index, 1);
			},
			// 文件上传成功的返回
			handleFilesSuccess(files) {
			  if (!Array.isArray(files)) {
			    files = [files]; // 如果不是数组，转为数组
			  }
			  const newResponses = files
			    .filter(file => file?.response) // 过滤掉没有response的项
			    .map(file => file.response);   // 提取response
			  this.fileListFJ = [...this.fileListFJ, ...newResponses];
			  this.pageInfo.busiAttachIds = this.fileListFJ && this.fileListFJ.length > 0 ? this.fileListFJ.map((file) =>file.id).join() : null;
			  console.log('更新后的文件列表', this.fileListFJ);
			},
			// 删除文件
			deleteFile(index) {
				this.fileListFJ.splice(index, 1);
				this.pageInfo.busiAttachIds = this.fileListFJ && this.fileListFJ.length > 0 ? this.fileListFJ.map((file) =>file.id).join() : null;
			},
			// 获取基本信息数据
			getpageInfo() {
				getauditInfo({
					id: this.businessId,
					businessType: this.businessType
				}).then((res) => {
					// this.pageInfo = res.data;
					this.pageInfo = this.autoMap(res.data, this.pageInfo);
					this.auditItems = res.data.auditItems;
					this.fileListFJ = res.data.busiAttachs ? res.data.busiAttachs : [];
					this.pageInfo.busiAttachIds = res.data.busiAttachIds ? res.data.busiAttachIds : '';
					if (this.actionType == 'add') {
						this.pageInfo.businessStatus = '';
						this.pageInfo.businessStatusName = '';
						this.businessId = res.data.businessId;
						this.pageInfo.createTime = timeFormat(new Date().getTime(), 'yyyy-mm-dd');
					}
					if (this.actionType == 'edit') {
						this.auditarry = res.data.auditorNames.split(',');
						this.pageInfo.holidayTypeNam = this.getLabelById(this.pageInfo.holidayType, this
							.holidaytypelist[0])
						if (res.data.businessStatus == 'DRAFT') {
							this.pageInfo.businessStatusName = '';
							this.pageInfo.businessStatus = '';
						}
					}
				});
			},
			// 选择人
			circulateSumint() {
				const chosedata = JSON.parse(uni.getStorageSync('selectPsersonData') || 'null') || null;
				if (!chosedata) return;
				const mergeData = (key) => {
					const oldValues = (this.pageInfo[key]?.split(',') || []).filter(Boolean);
					const newValues = (chosedata[key]?.split(',') || []).filter(Boolean);
					return [...new Set([...oldValues, ...newValues])].join(',');
				};
				this.pageInfo.auditorIds = mergeData('ids');
				this.pageInfo.auditorNames = mergeData('names');
				this.pageInfo.auditorAccounts = mergeData('mobiles');
				this.auditarry = this.pageInfo.auditorNames.split(',');
				uni.setStorageSync('selectPsersonData', null);
			},
			// 保存草稿
			sumitFn(type) {
				let isValid = false
				//必填校验
				if (
					this.pageInfo.content == '' || !this.pageInfo.content ||
					!this.pageInfo.holidayType || this.pageInfo.holidayType == '' ||
					!this.pageInfo.startTime || !this.pageInfo.endTime ||
					(this.pageInfo.businessStatus == 'UNDO' && this.pageInfo.auditorIds == '')
				) {
					uni.showToast({
						title: '单个文件大小不能超过10MB',
						icon: 'none'
					});
					isValid = false;
					return;
				}
				// 检查总大小
				const newTotalSize = this.totalSize + f.size;
				if (newTotalSize > this.maxTotalSize) {
					uni.showToast({
						title: '文件总大小不能超过50MB',
						icon: 'none'
					});
					isValid = false;
				}
				return isValid;
			},
			// 获取文件扩展名
			getFileExtension(filename) {
				if (!filename) return '';
				return filename.split('.').pop().toLowerCase();
			},
			// 处理文件上传后逻辑
			async afterRead(event) {
				const files = Array.isArray(event.file) ? event.file : [event.file];
				this.uploading = true;
				this.uploadErrors = [];
				try {
					// 并行处理所有文件上传，但按顺序收集结果
					const results = await Promise.allSettled(files.map((file, index) => this.uploadFilePromise(file
						.url, index)));
					// 处理成功的上传结果
					results.forEach((result, index) => {
						if (result.status === 'fulfilled') {
							if (result.value) {
								this.fileListFJ.push(result.value);
								this.FileSize();
							}
						} else {
							this.uploadErrors.push({
								index,
								error: result.reason
							});
						}
					});

					if (this.uploadErrors.length > 0) {
						uni.showToast({
							title: `部分文件上传失败(${this.uploadErrors.length}/${files.length})`,
							icon: 'none'
						});
					} else {
						uni.showToast({
							title: '全部文件上传成功',
							icon: 'none',
							duration: 1500
						});
					}
				} catch (error) {
					uni.showToast({
						title: '上传过程中发生错误',
						icon: 'none'
					});
				} finally {
					this.uploading = false;
				}
			},
			uploadFilePromise(url, fileIndex) {
				return new Promise((resolve, reject) => {
					const base_url = uni.getStorageSync('apiUrl') ? uni.getStorageSync('apiUrl') : '/api';
					uni.uploadFile({
						url: getRequestUrl() + '/app/workflow/business_attach/upload/HOLIDAY/' + this.pageInfo
							.businessId,
						filePath: url,
						name: 'files',
						header: {
							'ECWEB-JWTSSO-TOKEN': uni.getStorageSync('token')
						},
						success: (res) => {
							try {
								// 直接解析响应数据
								const responseData = JSON.parse(res.data);
								if (responseData && responseData.data && responseData.data[0]) {
									resolve(responseData.data[0]);
								} else {
									reject(new Error('服务器返回数据格式错误'));
								}
							} catch (parseError) {
								reject(parseError);
							}
						},
						fail: (err) => {
							reject(err);
						}
					});
				});
			},
			// 去选择人
			getPerson(title) {
				uni.navigateTo({
					url: '/documentManagement/selectPerson/circulate?title=' + title+'&checkIds='+this.pageInfo.auditorIds
				});
			},
			// 获取基本信息数据
			getpageInfo() {
				getauditInfo({
					id: this.businessId,
					businessType: this.businessType
				}).then((res) => {
					// this.pageInfo = res.data;
					this.pageInfo = this.autoMap(res.data, this.pageInfo);
					this.auditItems = res.data.auditItems;
					this.fileListFJ = res.data.busiAttachs ? res.data.busiAttachs : [];
					this.pageInfo.busiAttachIds = res.data.busiAttachIds ? res.data.busiAttachIds : '';
					if (this.actionType == 'add') {
						this.pageInfo.businessStatus = '';
						this.pageInfo.businessStatusName = '';
						this.businessId = res.data.businessId;
						this.pageInfo.createTime = timeFormat(new Date().getTime(), 'yyyy-mm-dd');
					}
					if (this.actionType == 'edit') {
						this.auditarry = res.data.auditorNames.split(',');
						this.pageInfo.holidayTypeNam = this.getLabelById(this.pageInfo.holidayType, this
							.holidaytypelist[0])
						if (res.data.businessStatus == 'DRAFT') {
							this.pageInfo.businessStatusName = '';
							this.pageInfo.businessStatus = '';
						}
					}
				});
			},
			// 选择人
			circulateSumint() {
				let chosedata = JSON.parse(uni.getStorageSync('selectPsersonData') || 'null') || '';
				if (chosedata) {
					this.auditarry = chosedata.names.split(',');
					this.pageInfo.auditorIds = chosedata.ids;
					this.pageInfo.auditorNames = chosedata.names;
				}
				uni.setStorageSync('selectPsersonData', null);
			},
			// 保存草稿
			sumitFn(type) {
				//必填校验
				if (
					this.pageInfo.content == '' || !this.pageInfo.content ||
					!this.pageInfo.holidayType || this.pageInfo.holidayType == '' ||
					!this.pageInfo.startTime || !this.pageInfo.endTime ||
					(this.pageInfo.businessStatus == 'UNDO' && this.pageInfo.auditorIds == '')
				) {
					uni.showToast({
						title: '请填写必填项！',
						icon: 'none',
						duration: 1500
					});
					return;
				}
				if (type === '保存') {
					getSaveDrafat(this.pageInfo).then((res) => {
						this.showToastAndNavigate(res);
					});
				} else if (type === '提交') {
					handelauditSubmit(this.pageInfo).then((res) => {
						this.showToastAndNavigate(res);
					});
				}
			},
			//提交保存成功公共处理
			showToastAndNavigate(res) {
				uni.showToast({
					title: res.msg,
					icon: 'none',
					duration: 1500
				});
				setTimeout(() => {
					uni.navigateTo({
						url: '/documentManagement/applicationleave/list?tabtype=2'
					});
				}, 1000);
			},
			// 选择路径选择
			businessStatuschange(val) {
				this.pageInfo.businessStatusName = val;
				this.pageInfo.businessStatus = val == '送审' ? 'UNDO' : val == '结束流程' ? 'DONE' : '';
				this.pageInfo.auditorIds = '';
				this.pageInfo.auditorNames = '';
				this.auditarry = [];
			},
			// 打开请假时间选择器
			opendateTime(type) {
				this.dateTimeTpey = type
				this.$refs.datetimePicker.open()
			},
			// 请假类型确认
			qjlxconfirm(e) {
				this.pageInfo.holidayTypeName = e.value[0].label
				this.pageInfo.holidayType = e.value[0].id
			},
			//请假时间确认
			datetimeconfirm(e) {
				if (this.dateTimeTpey == 'startTime') {
					this.pageInfo.startTime = timeFormat(e.value, 'yyyy-mm-dd hh:MM:ss');
				}
				if (this.dateTimeTpey == 'endTime') {
					this.pageInfo.endTime = timeFormat(e.value, 'yyyy-mm-dd hh:MM:ss');
				}
				console.log(this.pageInfo.startTime, this.pageInfo.endTime)
			},
			// 通过请假类型数组id获取leble的
			getLabelById(id, typeArray) {
				for (const type of typeArray) {
					if (type.id === id) {
						return type.label; // 匹配成功，返回标签
					}
				}
				return ""; // 未匹配到ID时返回默认值
			},
			autoMap(source, target) {
				const filteredSource = Object.keys(target).reduce((acc, key) => {
					if (source.hasOwnProperty(key)) {
						// 处理null值为''或[]
						const value = source[key];
						acc[key] = value === null ?
							(typeof target[key] === 'string' ? '' : []) :
							value;
					}
					return acc;
				}, {});

				return {
					...target,
					...filteredSource
				};
			},
			backfn() {
				uni.navigateBack({
					delta: 1
				});
			}
		}
	}
</script>
<style scoped lang="scss">
@import '../../style/documentmanage.scss';
::v-deep .uv-upload__wrap__preview {
	display: none;
}
</style>
